﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;

namespace XXF.Serialization
{
    /// <summary>
    /// XML序列化(gbk编码)提供类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class XmlProvider2<T>
    {
        public System.Text.Encoding encode = Encoding.GetEncoding("gbk");
        /// <summary>
        /// 序列化
        /// </summary>
        /// <returns></returns>
        public string Serializer(T obj)
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(T));
            using (MemoryStream stream = new MemoryStream())
            {
                serializer.WriteObject(stream, obj);
                return encode.GetString(stream.GetBuffer());
            }
        }
        
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <returns></returns>
        public T Deserialize(string xml)
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(T));
            using (MemoryStream stream = new MemoryStream(encode.GetBytes(xml)))
            {
                var r = (T)serializer.ReadObject(stream);
                return r;
            }
        }
    }
}
